const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');

const SECRET_KEY = 'your-secret-key-here'; // 在实际生产环境中应该使用环境变量

// 生成JWT token
const generateToken = (user) => {
    return jwt.sign(
        { 
            id: user.id, 
            username: user.username,
            role: user.role 
        },
        SECRET_KEY,
        { expiresIn: '24h' }
    );
};

// 验证JWT token的中间件
const authenticateToken = (req, res, next) => {
    const authHeader = req.headers['authorization'];
    console.log('Auth header:', authHeader); // 添加日志

    const token = authHeader && authHeader.split(' ')[1];
    console.log('Token:', token); // 添加日志

    if (!token) {
        console.error('No token provided');
        return res.status(401).json({ error: '未提供认证token' });
    }

    try {
        const user = jwt.verify(token, SECRET_KEY);
        console.log('Decoded user:', user); // 添加日志
        req.user = user;
        next();
    } catch (err) {
        console.error('Token verification failed:', err);
        return res.status(403).json({ error: 'token无效或已过期' });
    }
};

// 检查用户角色的中间件
const checkRole = (roles) => {
    return (req, res, next) => {
        console.log('Checking role for user:', req.user); // 添加日志
        console.log('Required roles:', roles); // 添加日志

        if (!req.user) {
            console.error('No user found in request');
            return res.status(401).json({ error: '未认证' });
        }

        if (!req.user.role) {
            console.error('User has no role:', req.user);
            return res.status(403).json({ error: '用户角色未定义' });
        }

        if (!roles.includes(req.user.role)) {
            console.error('User role not allowed:', req.user.role);
            return res.status(403).json({ error: '权限不足' });
        }

        console.log('Role check passed for user:', req.user.username); // 添加日志
        next();
    };
};

// 密码加密
const hashPassword = async (password) => {
    const salt = await bcrypt.genSalt(10);
    return bcrypt.hash(password, salt);
};

// 密码验证
const comparePassword = async (password, hash) => {
    return bcrypt.compare(password, hash);
};

module.exports = {
    generateToken,
    authenticateToken,
    checkRole,
    hashPassword,
    comparePassword
}; 